const { getApiUrl } = require('../../config/config.js');

Page({
  data: {
    // 页面状态
    currentTab: 'browse',
    loading: false,
    refreshing: false,
    
    // 学习资料列表
    materialList: [],
    myMaterials: [],
    pendingMaterials: [],
    hasMore: true,
    current: 1,
    size: 10,
    total: 0,
    
    // 统计数据
    myMaterialsCount: 0,
    totalDownloads: 0,
    pendingCount: 0,
    
    // 筛选条件
    filterOptions: {
      subjectType: '',
      fileType: '',
      collegeName: '',
      academicYear: '',
      semester: '',
      orderBy: 'time'
    },
    
    // 基础数据选项
    subjects: [{ value: '', label: '请选择学科分类' }],
    colleges: [{ value: '', label: '请选择所属学院' }],
    academicYears: [{ value: '', label: '请选择学年' }],
    semesters: [
      { value: '', label: '请选择学期' },
      { value: 1, label: '第一学期' },
      { value: 2, label: '第二学期' }
    ],
    fileTypes: [
      { value: '', label: '全部类型' },
      { value: 'pdf', label: 'PDF文档' },
      { value: 'doc', label: 'Word文档' },
      { value: 'ppt', label: 'PPT演示' },
      { value: 'xls', label: 'Excel表格' },
      { value: 'image', label: '图片资料' },
      { value: 'video', label: '视频教程' }
    ],
    
    // 选择器索引
    subjectSelectedIndex: 0,
    collegeSelectedIndex: 0,
    academicYearSelectedIndex: 0,
    semesterSelectedIndex: 0,
    
    // 上传相关
    uploadForm: {
      title: '',
      description: '',
      subjectType: '',
      collegeName: '',
      academicYear: '',
      semester: '',
      files: []
    },
    uploading: false,
    
    // 搜索
    searchKeyword: '',
    showSearchBar: false,
    
    // 用户信息
    userInfo: null,
    token: ''
  },

  onLoad() {
    this.initPage();
  },

  onShow() {
    this.refreshCurrentTab();
  },

  onPullDownRefresh() {
    this.refreshCurrentTab();
  },

  onReachBottom() {
    if (this.data.currentTab === 'browse' && this.data.hasMore) {
      this.loadMoreMaterials();
    }
  },

  // 初始化页面
  async initPage() {
    try {
      const userInfo = wx.getStorageSync('userInfo');
      const token = wx.getStorageSync('token') || '';
      
      this.setData({ 
        userInfo,
        token
      });
      
      // 并行加载基础数据
      console.log('开始加载基础数据...');
      await Promise.all([
        this.loadSubjects(),
        this.loadColleges(),
        this.loadAcademicYears()
      ]);
      console.log('基础数据加载完成:', {
        subjects: this.data.subjects.length,
        colleges: this.data.colleges.length,
        academicYears: this.data.academicYears.length
      });
      
      // 加载资料列表
      await this.loadMaterials();
      
      // 如果已登录，加载待审核资料数量
      if (this.data.token) {
        this.loadPendingMaterials();
      }
      
    } catch (error) {
      console.error('页面初始化失败:', error);
      this.showError('加载失败');
    }
  },

  // 加载学科分类
  async loadSubjects() {
    try {
      console.log('开始请求学科分类...');
              const res = await this.request('/api/file/learning-material/subjects');
        console.log('学科分类响应:', res);
        
        if (res.code === 200 || res.code === 0) {
        console.log('学科分类原始数据:', res.data);
        const subjects = [
          { value: '', label: '请选择学科分类' },
          ...res.data.map(item => ({ value: item, label: item }))
        ];
        console.log('处理后的学科数据:', subjects);
        this.setData({ subjects });
        console.log('学科数据已设置到页面');
      } else {
        console.error('学科分类请求失败:', res.message);
      }
    } catch (error) {
      console.error('加载学科失败:', error);
    }
  },

  // 加载学院列表
  async loadColleges() {
    try {
      console.log('开始请求学院列表...');
              const res = await this.request('/api/file/learning-material/colleges');
        console.log('学院列表响应:', res);
        
        if (res.code === 200 || res.code === 0) {
        console.log('学院原始数据:', res.data);
        const colleges = [
          { value: '', label: '请选择所属学院' },
          ...res.data.map(item => ({ value: item, label: item }))
        ];
        console.log('处理后的学院数据:', colleges);
        this.setData({ colleges });
        console.log('学院数据已设置到页面');
      } else {
        console.error('学院列表请求失败:', res.message);
      }
    } catch (error) {
      console.error('加载学院失败:', error);
    }
  },

  // 加载学年列表
  async loadAcademicYears() {
    try {
      console.log('开始请求学年列表...');
              const res = await this.request('/api/file/learning-material/academic-years');
        console.log('学年列表响应:', res);
        
        if (res.code === 200 || res.code === 0) {
        console.log('学年原始数据:', res.data);
        const academicYears = [
          { value: '', label: '请选择学年' },
          ...res.data.map(item => ({ value: item, label: item }))
        ];
        console.log('处理后的学年数据:', academicYears);
        this.setData({ academicYears });
        console.log('学年数据已设置到页面');
      } else {
        console.error('学年列表请求失败:', res.message);
      }
    } catch (error) {
      console.error('加载学年失败:', error);
    }
  },

  // 切换Tab
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ 
      currentTab: tab,
      current: 1,
      hasMore: true
    });
    
    if (tab === 'browse') {
      this.loadMaterials(true);
    } else if (tab === 'my') {
      this.loadMyMaterials(true);
    } else if (tab === 'pending') {
      this.loadPendingMaterials(true);
    }
  },

  // 刷新当前Tab
  refreshCurrentTab() {
    const { currentTab } = this.data;
    
    this.setData({ 
      current: 1,
      hasMore: true
    });
    
    if (currentTab === 'browse') {
      this.loadMaterials(true);
    } else if (currentTab === 'my') {
      this.loadMyMaterials(true);
    } else if (currentTab === 'pending') {
      this.loadPendingMaterials(true);
    }
    
    wx.stopPullDownRefresh();
  },

  // 加载公开资料
  async loadMaterials(refresh = false) {
    if (this.data.loading && !refresh) return;
    
    const current = refresh ? 1 : this.data.current;
    
    this.setData({
      loading: true,
      refreshing: refresh
    });

    try {
      const params = {
        current,
        size: this.data.size,
        keyword: this.data.searchKeyword,
        ...this.data.filterOptions
      };

      // 清空空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === undefined) {
          delete params[key];
        }
      });

      const res = await this.request('/api/file/learning-material/public', 'GET', params);
      
      if (res.code === 200 || res.code === 0) {
        const newMaterials = this.formatMaterialsList(res.data.records);
        const materialList = refresh ? newMaterials : [...this.data.materialList, ...newMaterials];
        
        this.setData({
          materialList,
          current: current + 1,
          total: res.data.total,
          hasMore: materialList.length < res.data.total
        });
      }
    } catch (error) {
      console.error('加载资料失败:', error);
      this.showError('加载失败');
    } finally {
      this.setData({
        loading: false,
        refreshing: false
      });
    }
  },

  // 加载更多资料
  loadMoreMaterials() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMaterials();
    }
  },

  // 加载我的资料
  async loadMyMaterials(refresh = false) {
    if (!this.checkLogin()) return;
    
    this.setData({ loading: true });

    try {
      const params = {
        current: refresh ? 1 : this.data.current,
        size: this.data.size
      };

      const res = await this.request('/api/file/learning-material/my', 'GET', params);
      
      if (res.code === 200 || res.code === 0) {
        const formattedMaterials = this.formatMaterialsList(res.data.records);
        const totalDownloads = formattedMaterials.reduce((sum, item) => sum + item.downloadCount, 0);
        
        this.setData({
          myMaterials: formattedMaterials,
          myMaterialsCount: res.data.total,
          totalDownloads
        });
      }
    } catch (error) {
      console.error('加载我的资料失败:', error);
      this.showError('加载失败');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载待审核资料
  async loadPendingMaterials(refresh = false) {
    if (!this.checkLogin()) return;
    
    this.setData({ loading: true });

    try {
      const params = {
        current: refresh ? 1 : this.data.current,
        size: this.data.size
      };

      const res = await this.request('/api/file/learning-material/pending', 'GET', params);
      
      if (res.code === 200 || res.code === 0) {
        const formattedMaterials = this.formatMaterialsList(res.data.records);
        
        this.setData({
          pendingMaterials: formattedMaterials,
          pendingCount: res.data.total
        });
      }
    } catch (error) {
      console.error('加载待审核资料失败:', error);
      this.showError('加载失败');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 格式化资料列表数据
  formatMaterialsList(materials) {
    return materials.map(item => ({
      ...item,
      fileSizeFormatted: this.formatFileSize(item.fileSize),
      createTimeFormatted: this.formatTime(item.createTime),
      fileTypeIcon: this.getFileTypeIcon(item.fileType),
      auditStatusColor: this.getAuditStatusColor(item.auditStatus)
    }));
  },

  // 获取审核状态颜色
  getAuditStatusColor(status) {
    const colorMap = {
      0: '#ff9800', // 待审核 - 橙色
      1: '#4caf50', // 通过 - 绿色
      2: '#f44336'  // 拒绝 - 红色
    };
    return colorMap[status] || '#999';
  },

  // 搜索相关方法
  toggleSearchBar() {
    this.setData({
      showSearchBar: !this.data.showSearchBar
    });
  },

  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  onSearchConfirm() {
    this.setData({ 
      current: 1,
      hasMore: true
    });
    this.loadMaterials(true);
  },

  clearSearch() {
    this.setData({
      searchKeyword: '',
      showSearchBar: false,
      current: 1,
      hasMore: true
    });
    this.loadMaterials(true);
  },

  // 筛选方法
  showFilterModal() {
    wx.showActionSheet({
      itemList: ['按学科筛选', '按学院筛选', '按学年筛选', '按文件类型筛选', '排序方式', '清空筛选'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0: this.showSubjectFilter(); break;
          case 1: this.showCollegeFilter(); break;
          case 2: this.showAcademicYearFilter(); break;
          case 3: this.showFileTypeFilter(); break;
          case 4: this.showSortOptions(); break;
          case 5: this.clearAllFilters(); break;
        }
      }
    });
  },

  showSubjectFilter() {
    const itemList = this.data.subjects.map(item => item.label);
    
    wx.showActionSheet({
      itemList,
      success: (res) => {
        const selectedSubject = this.data.subjects[res.tapIndex];
        this.setData({
          'filterOptions.subjectType': selectedSubject.value,
          current: 1,
          hasMore: true
        });
        this.loadMaterials(true);
      }
    });
  },

  showCollegeFilter() {
    const itemList = this.data.colleges.map(item => item.label);
    
    wx.showActionSheet({
      itemList,
      success: (res) => {
        const selectedCollege = this.data.colleges[res.tapIndex];
        this.setData({
          'filterOptions.collegeName': selectedCollege.value,
          current: 1,
          hasMore: true
        });
        this.loadMaterials(true);
      }
    });
  },

  showAcademicYearFilter() {
    const itemList = this.data.academicYears.map(item => item.label);
    
    wx.showActionSheet({
      itemList,
      success: (res) => {
        const selectedYear = this.data.academicYears[res.tapIndex];
        this.setData({
          'filterOptions.academicYear': selectedYear.value,
          current: 1,
          hasMore: true
        });
        this.loadMaterials(true);
      }
    });
  },

  showFileTypeFilter() {
    const itemList = this.data.fileTypes.map(item => item.label);
    
    wx.showActionSheet({
      itemList,
      success: (res) => {
        const selectedType = this.data.fileTypes[res.tapIndex];
        this.setData({
          'filterOptions.fileType': selectedType.value,
          current: 1,
          hasMore: true
        });
        this.loadMaterials(true);
      }
    });
  },

  showSortOptions() {
    const sortOptions = [
      { value: 'time', label: '按时间排序' },
      { value: 'download', label: '按下载量排序' },
      { value: 'view', label: '按浏览量排序' }
    ];
    
    const itemList = sortOptions.map(item => item.label);
    
    wx.showActionSheet({
      itemList,
      success: (res) => {
        const selectedSort = sortOptions[res.tapIndex];
        this.setData({
          'filterOptions.orderBy': selectedSort.value,
          current: 1,
          hasMore: true
        });
        this.loadMaterials(true);
      }
    });
  },

  clearAllFilters() {
    this.setData({
      filterOptions: {
        subjectType: '',
        fileType: '',
        collegeName: '',
        academicYear: '',
        semester: '',
        orderBy: 'time'
      },
      searchKeyword: '',
      current: 1,
      hasMore: true
    });
    this.loadMaterials(true);
  },

  // 表单输入处理
  onUploadFormInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`uploadForm.${field}`]: value
    });
  },

  // 选择器变化处理
  onPickerChange(e) {
    const field = e.currentTarget.dataset.field;
    const options = e.currentTarget.dataset.options;
    const index = parseInt(e.detail.value);
    
    console.log('选择器变化:', { field, options, index, dataLength: this.data[options]?.length });
    
    // 检查数据是否存在
    if (!this.data[options] || !this.data[options][index]) {
      console.error(`选择器数据不存在: ${options}[${index}]`, {
        optionsData: this.data[options],
        dataLength: this.data[options]?.length
      });
      return;
    }
    
    const selectedOption = this.data[options][index];
    
    // 更新表单数据和选择器索引
    const updateData = {
      [`uploadForm.${field}`]: selectedOption.value
    };
    
    // 更新对应的选择器索引
    switch(field) {
      case 'subjectType':
        updateData.subjectSelectedIndex = index;
        break;
      case 'collegeName':
        updateData.collegeSelectedIndex = index;
        break;
      case 'academicYear':
        updateData.academicYearSelectedIndex = index;
        break;
      case 'semester':
        updateData.semesterSelectedIndex = index;
        break;
    }
    
    this.setData(updateData);
  },

  // 文件选择和上传
  chooseFiles() {
    if (this.data.uploading) return;

    // 检查是否在开发者工具中
    const isDevTools = wx.getSystemInfoSync().platform === 'devtools';
    this.setData({ isDevTools });
    
    const itemList = isDevTools 
      ? ['选择图片', '拍照上传', '选择文档(真机支持)']
      : ['选择文档', '选择图片', '拍照上传'];

    wx.showActionSheet({
      itemList,
      success: (res) => {
        if (isDevTools) {
          switch (res.tapIndex) {
            case 0: this.chooseImages(); break;
            case 1: this.takePhoto(); break;
            case 2: this.showDocumentUploadOptions(); break;
          }
        } else {
          switch (res.tapIndex) {
            case 0: this.chooseDocuments(); break;
            case 1: this.chooseImages(); break;
            case 2: this.takePhoto(); break;
          }
        }
      }
    });
  },

  // 选择文档
  chooseDocuments() {
    // 检查运行环境
    const systemInfo = wx.getSystemInfoSync();
    const isDevTools = systemInfo.platform === 'devtools';
    
    if (isDevTools) {
      // 开发者工具中的替代方案
      this.showDocumentUploadOptions();
      return;
    }

    // 真机环境，尝试使用文档选择API
    if (typeof wx.chooseMessageFile === 'function') {
      wx.chooseMessageFile({
        count: 5,
        type: 'file',
        success: (res) => {
          console.log('选择文档成功:', res);
          this.handleFilesSelected(res.tempFiles);
        },
        fail: (error) => {
          console.error('chooseMessageFile失败:', error);
          // 如果chooseMessageFile失败，尝试使用chooseMedia
          this.tryChooseMedia();
        }
      });
    } else {
      // API不存在，尝试其他方式
      this.tryChooseMedia();
    }
  },

  // 尝试使用chooseMedia API
  tryChooseMedia() {
    if (typeof wx.chooseMedia === 'function') {
      wx.chooseMedia({
        count: 5,
        mediaType: ['image'], // 在不支持文档时，至少支持图片
        sourceType: ['album'],
        success: (res) => {
          console.log('chooseMedia成功:', res);
          const tempFiles = res.tempFiles.map(file => ({
            path: file.tempFilePath,
            name: `file_${Date.now()}.${file.fileType || 'jpg'}`,
            size: file.size || 0
          }));
          this.handleFilesSelected(tempFiles);
        },
        fail: (error) => {
          console.error('chooseMedia失败:', error);
          this.showDocumentUploadOptions();
        }
      });
    } else {
      // 都不支持，显示提示
      this.showDocumentUploadOptions();
    }
  },

  // 显示文档上传选项（开发者工具替代方案）
  showDocumentUploadOptions() {
    wx.showModal({
      title: '文档上传提示',
      content: '开发者工具暂不支持文档选择，请在真机上测试。\n\n或者您可以：\n1. 选择图片上传\n2. 拍照上传\n3. 在真机上测试完整功能',
      showCancel: true,
      confirmText: '选择图片',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.chooseImages();
        }
      }
    });
  },

  // 选择图片
  chooseImages() {
    wx.chooseImage({
      count: 5,
      sourceType: ['album'],
      success: (res) => {
        const tempFiles = res.tempFilePaths.map((path, index) => ({
          path,
          name: `image_${Date.now()}_${index}.jpg`,
          size: 0
        }));
        this.handleFilesSelected(tempFiles);
      }
    });
  },

  // 拍照
  takePhoto() {
    wx.chooseImage({
      count: 1,
      sourceType: ['camera'],
      success: (res) => {
        const tempFiles = res.tempFilePaths.map(path => ({
          path,
          name: `photo_${Date.now()}.jpg`,
          size: 0
        }));
        this.handleFilesSelected(tempFiles);
      }
    });
  },

  // 处理选择的文件
  async handleFilesSelected(tempFiles) {
    if (tempFiles.length === 0) return;
    
    this.setData({ uploading: true });
    
    wx.showLoading({
      title: '上传中...',
      mask: true
    });

    try {
      const uploadedFiles = [];
      
      for (let file of tempFiles) {
        try {
          const result = await this.uploadSingleFile(file);
          if (result.success) {
            uploadedFiles.push({
              id: Date.now() + Math.random(),
              fileName: file.name,
              url: result.url,
              fileSize: file.size,
              fileType: this.getFileTypeFromName(file.name),
              fileSizeFormatted: this.formatFileSize(file.size),
              fileTypeIcon: this.getFileTypeIcon(this.getFileTypeFromName(file.name))
            });
          }
        } catch (error) {
          console.error(`文件 ${file.name} 上传失败:`, error);
        }
      }
      
      if (uploadedFiles.length > 0) {
        this.setData({
          'uploadForm.files': [...this.data.uploadForm.files, ...uploadedFiles]
        });
        
        wx.showToast({
          title: `成功上传${uploadedFiles.length}个文件`,
          icon: 'success'
        });
      } else {
        this.showError('文件上传失败');
      }
      
    } catch (error) {
      console.error('文件上传失败:', error);
      this.showError('上传失败');
    } finally {
      wx.hideLoading();
      this.setData({ uploading: false });
    }
  },

  // 上传单个文件
  uploadSingleFile(file) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: getApiUrl('/upload/file'),
        filePath: file.path,
        name: 'file',
        formData: {
          fileType: this.detectFileType(file.name),
          folder: this.generateFolderPath()
        },
        header: {
          'Authorization': this.data.token
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.code === 200 || data.code === 0) {
              resolve({
                success: true,
                url: data.data.url || data.data.fileUrl
              });
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (error) {
            reject(new Error('响应解析失败'));
          }
        },
        fail: reject
      });
    });
  },

  // 删除文件
  deleteFile(e) {
    const index = e.currentTarget.dataset.index;
    const files = [...this.data.uploadForm.files];
    files.splice(index, 1);
    
    this.setData({
      'uploadForm.files': files
    });
  },

  // 提交资料
  async submitMaterial() {
    if (!this.validateUploadForm()) return;
    if (!this.checkLogin()) return;

    this.setData({ uploading: true });
    
    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    try {
      const { title, description, subjectType, collegeName, academicYear, semester, files } = this.data.uploadForm;
      
      // 为每个文件创建学习资料记录
      const promises = files.map(file => {
        const materialData = {
          userId: this.data.userInfo.id,
          title: files.length > 1 ? `${title} - ${file.fileName}` : title,
          description: description || '',
          fileUrl: file.url,
          fileName: file.fileName,
          fileSize: file.fileSize,
          fileType: file.fileType,
          collegeName,
          subjectType,
          academicYear,
          semester: parseInt(semester)
        };
        
        return this.request('/api/file/learning-material/create', 'POST', materialData);
      });
      
      const results = await Promise.all(promises);
      const successCount = results.filter(res => res.code === 200 || res.code === 0).length;
      
      if (successCount > 0) {
        wx.showToast({
          title: `成功提交${successCount}个资料`,
          icon: 'success'
        });
        
        // 重置表单
        this.resetUploadForm();
        
        // 切换到待审核页面
        this.setData({ currentTab: 'pending' });
        this.loadPendingMaterials(true);
      } else {
        this.showError('提交失败');
      }
      
    } catch (error) {
      console.error('提交资料失败:', error);
      this.showError('提交失败');
    } finally {
      wx.hideLoading();
      this.setData({ uploading: false });
    }
  },

  // 验证上传表单
  validateUploadForm() {
    const { title, subjectType, collegeName, academicYear, semester, files } = this.data.uploadForm;
    
    if (!title.trim()) {
      this.showError('请输入资料标题');
      return false;
    }
    
    if (!subjectType) {
      this.showError('请选择学科分类');
      return false;
    }
    
    if (!collegeName) {
      this.showError('请选择所属学院');
      return false;
    }
    
    if (!academicYear) {
      this.showError('请选择学年');
      return false;
    }
    
    if (!semester && semester !== 1 && semester !== 2) {
      this.showError('请选择学期');
      return false;
    }
    
    if (files.length === 0) {
      this.showError('请上传至少一个文件');
      return false;
    }
    
    return true;
  },

  
  // 重置上传表单
  resetUploadForm() {
    this.setData({
      uploadForm: {
        title: '',
        description: '',
        subjectType: '',
        collegeName: '',
        academicYear: '',
        semester: '',
        files: []
      },
      // 重置选择器索引
      subjectSelectedIndex: 0,
      collegeSelectedIndex: 0,
      academicYearSelectedIndex: 0,
      semesterSelectedIndex: 0
    });
  },

  // 预览资料
  previewMaterial(e) {
    const material = e.currentTarget.dataset.material;
    this.showMaterialDetail(material);
  },

  // 显示资料详情
  showMaterialDetail(material) {
    const statusText = this.getAuditStatusText(material.auditStatus);
    const content = `描述：${material.description || '无'}\n学科：${material.subjectType}\n学院：${material.collegeName}\n学年：${material.academicYear}\n学期：第${material.semester}学期\n文件大小：${material.fileSizeFormatted}\n上传者：${material.uploaderUsername || '匿名'}\n浏览次数：${material.viewCount || 0}\n下载次数：${material.downloadCount}\n审核状态：${statusText}\n上传时间：${material.createTimeFormatted}`;
    
    wx.showModal({
      title: material.title,
      content,
      confirmText: material.auditStatus === 1 ? '下载' : '确定',
      cancelText: '关闭',
      success: (res) => {
        if (res.confirm && material.auditStatus === 1) {
          this.downloadMaterial({ currentTarget: { dataset: { material } } });
        }
      }
    });
  },

  // 获取审核状态文本
  getAuditStatusText(status) {
    const statusMap = {
      0: '待审核',
      1: '审核通过',
      2: '审核拒绝'
    };
    return statusMap[status] || '未知状态';
  },

  // 下载资料
  downloadMaterial(e) {
    const material = e.currentTarget.dataset.material;
    
    if (material.auditStatus !== 1) {
      this.showError('该资料尚未通过审核，无法下载');
      return;
    }
    
    wx.showLoading({
      title: '准备下载...',
      mask: true
    });
    
    wx.downloadFile({
      url: material.filePath,
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          wx.openDocument({
            filePath: res.tempFilePath,
            showMenu: true,
            success: () => {
              // 增加下载次数（可选：调用后端API）
              this.incrementDownloadCount(material.id);
            },
            fail: () => {
              wx.showToast({
                title: '打开文件失败',
                icon: 'none'
              });
            }
          });
        } else {
          this.showError('下载失败');
        }
      },
      fail: () => {
        wx.hideLoading();
        this.showError('下载失败');
      }
    });
  },

  // 增加下载次数
  async incrementDownloadCount(materialId) {
    try {
      await this.request(`/api/file/learning-material/${materialId}/download`, 'POST');
    } catch (error) {
      console.error('更新下载次数失败:', error);
    }
  },

  // 删除我的资料
  deleteMaterial(e) {
    const material = e.currentTarget.dataset.material;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除资料"${material.title}"吗？删除后无法恢复。`,
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          this.performDeleteMaterial(material.id);
        }
      }
    });
  },

  // 执行删除操作
  async performDeleteMaterial(materialId) {
    wx.showLoading({
      title: '删除中...',
      mask: true
    });

    try {
      const res = await this.request(`/api/file/learning-material/${materialId}`, 'DELETE');
      
      if (res.code === 200 || res.code === 0) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 刷新相关列表
        if (this.data.currentTab === 'my') {
          this.loadMyMaterials(true);
        } else if (this.data.currentTab === 'pending') {
          this.loadPendingMaterials(true);
        }
      } else {
        this.showError(res.message || '删除失败');
      }
      
    } catch (error) {
      console.error('删除资料失败:', error);
      this.showError('删除失败');
    } finally {
      wx.hideLoading();
    }
  },

  // 网络请求封装
  request(url, method = 'GET', data = {}) {
    return new Promise((resolve, reject) => {
      const requestConfig = {
        url: getApiUrl(url),
        method,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: reject
      };

      // 添加认证头
      if (this.data.token) {
        requestConfig.header['Authorization'] = this.data.token;
      }

      // 根据请求方法处理数据
      if (method === 'GET') {
        requestConfig.data = data;
      } else {
        requestConfig.data = data;
      }

      wx.request(requestConfig);
    });
  },

  // 检查登录状态
  checkLogin() {
    if (!this.data.userInfo || !this.data.token) {
      wx.showModal({
        title: '需要登录',
        content: '请先登录后再使用此功能',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return false;
    }
    return true;
  },

  // 显示错误信息
  showError(message) {
    wx.showToast({
      title: message || '操作失败',
      icon: 'none',
      duration: 2000
    });
  },

  // 工具方法：格式化文件大小
  formatFileSize(size) {
    if (!size) return '0B';
    
    if (size < 1024) {
      return size + 'B';
    } else if (size < 1024 * 1024) {
      return (size / 1024).toFixed(1) + 'KB';
    } else if (size < 1024 * 1024 * 1024) {
      return (size / (1024 * 1024)).toFixed(1) + 'MB';
    } else {
      return (size / (1024 * 1024 * 1024)).toFixed(1) + 'GB';
    }
  },

  // 工具方法：格式化时间
  formatTime(timeStr) {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now - date;

    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`;
    }
    // 小于24小时
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`;
    }
    // 小于30天
    if (diff < 2592000000) {
      return `${Math.floor(diff / 86400000)}天前`;
    }
    // 其他情况显示具体日期
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 工具方法：获取文件类型图标
  getFileTypeIcon(fileType) {
    const iconMap = {
      pdf: '/images/icons/pdf.png',
      doc: '/images/icons/doc.png',
      docx: '/images/icons/doc.png',
      ppt: '/images/icons/ppt.png',
      pptx: '/images/icons/ppt.png',
      xls: '/images/icons/excel.png',
      xlsx: '/images/icons/excel.png',
      txt: '/images/icons/txt.png',
      jpg: '/images/icons/image.png',
      jpeg: '/images/icons/image.png',
      png: '/images/icons/image.png',
      gif: '/images/icons/image.png',
      webp: '/images/icons/image.png',
      mp4: '/images/icons/video.png',
      avi: '/images/icons/video.png',
      mov: '/images/icons/video.png',
      mp3: '/images/icons/audio.png',
      wav: '/images/icons/audio.png',
      zip: '/images/icons/zip.png',
      rar: '/images/icons/zip.png'
    };
    
    return iconMap[fileType?.toLowerCase()] || '/images/icons/file.png';
  },

  // 工具方法：从文件名获取文件类型
  getFileTypeFromName(fileName) {
    if (!fileName) return 'unknown';
    
    const extension = fileName.split('.').pop()?.toLowerCase();
    if (!extension) return 'unknown';
    
    // 文档类型
    if (['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt'].includes(extension)) {
      return extension;
    }
    
    // 图片类型
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
      return 'image';
    }
    
    // 视频类型
    if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(extension)) {
      return 'video';
    }
    
    // 音频类型
    if (['mp3', 'wav', 'aac', 'flac', 'm4a'].includes(extension)) {
      return 'audio';
    }
    
    // 压缩文件
    if (['zip', 'rar', '7z', 'tar', 'gz'].includes(extension)) {
      return 'archive';
    }
    
    return extension;
  },

  // 工具方法：检测文件类型（用于上传）
  detectFileType(fileName) {
    if (!fileName) return 'other';
    
    const extension = fileName.split('.').pop()?.toLowerCase();
    if (!extension) return 'other';

    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
      return 'image';
    }
    
    if (['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt'].includes(extension)) {
      return 'document';
    }
    
    if (['mp4', 'avi', 'mov', 'wmv', 'flv'].includes(extension)) {
      return 'video';
    }
    
    if (['mp3', 'wav', 'aac', 'flac'].includes(extension)) {
      return 'audio';
    }
    
    return 'other';
  },

  // 工具方法：生成文件夹路径
  generateFolderPath() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `learning-materials/${year}/${month}/${day}`;
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: '树岛 - 学习资源',
      path: '/pages/study/study',
      imageUrl: '/images/share/study.png'
    };
  },

  // 页面分享到朋友圈
  onShareTimeline() {
    return {
      title: '树岛 - 学习资源分享平台',
      imageUrl: '/images/share/study.png'
    };
  }
});
        